from http.server import HTTPServer, BaseHTTPRequestHandler
import json, subprocess
from logging import warning
from multiprocessing import Process
from traceback import print_stack
 
class Resquest(BaseHTTPRequestHandler):
  def do_GET(self):
    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.send_header('Access-Control-Allow-Origin', '*')
    self.end_headers()

    try:
      cmd = 'python3 ./staking_deposit/cli/new_mnemonic.py'
      mnemonic = subprocess.getoutput(cmd)
      data = {'mnemonic': mnemonic}
      self.wfile.write(json.dumps(data).encode())
    except Exception as e:
      print_stack()

  def do_POST(self):
    self.send_response(200)
    self.send_header('Content-type', 'application/json')
    self.send_header('Access-Control-Allow-Origin', '*')
    self.end_headers()

    try: 
      req_datas = self.rfile.read(int(self.headers['content-length']))
      body = req_datas.decode()
      d: dict = json.loads(body)
      print(body)
      mnemonic = d['mnemonic']
      password = d['password']
      chain = d['chain']
      validator_start_index = d['validator_start_index']
      num_validators = d['num_validators']

      # warning_str = 'default to prater'
      # chain = 'prater'

      # if d.get('chain') is not None:
      #   chain = d['chain']
      #   warning_str = None

      cmd = f'python3 ./staking_deposit/cli/generate_keys.py {mnemonic}///{password}///{chain}///{validator_start_index}///{num_validators}'
      data_str = subprocess.getoutput(cmd)
      data = json.loads(data_str)
      # if warning_str is not None:
      #   data['warning'] = warning_str
      self.wfile.write(json.dumps(data).encode())
    except Exception as e:
      print(e)
 
def start_serve_data():
  host = ('0.0.0.0', 8002)
  server = HTTPServer(host, Resquest)
  server.serve_forever()

if __name__ == '__main__':
  p = Process(target=start_serve_data)
  p.start()